package com.jushu.storbox.view.dialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;

import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.jushu.storbox.R;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.serviceV2.ApkVersionClientV2;
import com.huawei.sharedrive.sdk.android.serviceV2.IApkDownloadProcessor;

public class ProgressDownloader {
	private Context mContext;
	private static ProgressDownloader mInstance;
	private String mApkName;
	private String mUrl;
	private long mTotalSize;
	private MyThread mThread;
	private Handler mHandler;
	private CloudProgressDialog mUpdateDialog;

	private RemoteViews view = null;
	private Builder mNotification;
	private NotificationManager manager = null;
	
	public static final Object object = new Object();
	

	private ProgressDownloader(Context context, String apkName, String url,
			long totalSize) {
		mContext = context;
		mApkName = apkName;
		mUrl = url;
		mTotalSize = totalSize;
		initHandler();
	}
	
	public static ProgressDownloader getInstance(){
		return mInstance;
	}

	public static ProgressDownloader getInstance(Context context,
			String apkName, String url, long totalSize) {
		if (mInstance == null) {
			mInstance = new ProgressDownloader(context, apkName, url, totalSize);
		}
		return mInstance;
	}

	private void initHandler() {
		try {
			mHandler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case 8000:// show download dialog
						Log.i("liuxiang", "8000 run");
						SharedPreferences settings0 = mContext
								.getSharedPreferences(ClientConfig.settings,
										Context.MODE_APPEND);
						Editor editor0 = settings0.edit();
						editor0.putInt(
								ClientConfig.UPGRADE_APK_DOWNLOAD_STATUS,
								Constant.APK_NOW_IS_DOWNLOADING);
						editor0.commit();
						try {
							mUpdateDialog = new CloudProgressDialog(mContext, R.style.progress_dialog);
							mUpdateDialog.setSystemDialog();
							mUpdateDialog.needShowDialog();
//							mUpdateDialog = new ProgressDialog(mContext);
//							mUpdateDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//							mUpdateDialog.setCanceledOnTouchOutside(true);
//							mUpdateDialog.show();
						} catch (Exception e) {
							Log.i("liuxiang", "create dialog error" + e.getMessage());
						}
						
						
//						mUpdateDialog
//								.updateMessage(mContext
//										.getString(R.string.main_activity_update_now_download));

						mUpdateDialog
						.updateMessage(0 + "%");
						
//						mUpdateDialog.setMessage(0 + "%");
						
						if (manager == null) {
							manager = (NotificationManager) mContext
									.getSystemService(Context.NOTIFICATION_SERVICE);
						}
						if (view == null) {
							view = new RemoteViews(mContext.getPackageName(),
									R.layout.view_notify_progress);
						}
						if(mNotification == null){
							mNotification = new NotificationCompat.Builder(mContext).setSmallIcon(R.drawable.icon_logo)
									  .setContentTitle("OneBox")
									  .setContentText(mContext.getResources().getString(R.string.main_activity_update_now_download));
//									mNotification.setAutoCancel(false);
									mNotification.setTicker(mContext.getResources().getString(R.string.main_activity_update_now_download));
						}
//						mNotification.icon = R.drawable.icon_logo;
//						mNotification.tickerText = "OneBox";
//						mNotification.largeIcon = BitmapFactory
//								.decodeResource(mContext.getResources(),
//										R.drawable.icon_logo);
						view.setProgressBar(R.id.progressBar, 100, 0, false);
						view.setTextViewText(R.id.tv_progress, 0 + "%");
//						mNotification.contentView = view;
						manager.notify(0, mNotification.build());

						break;
					case 8001:// update download dialog
						int perProgress = (Integer) msg.obj;
						if(mUpdateDialog != null && mUpdateDialog.isShowing()){
//							mUpdateDialog
//								.updateMessage(mContext
//										.getString(R.string.main_activity_update_now_download)
//										+ perProgress + "%");
							mUpdateDialog
							.updateMessage(perProgress + "%");
//							mUpdateDialog.setMessage(perProgress + "%");
//							mUpdateDialog.setProgress(Integer.valueOf(perProgress));
						}

						mNotification.setProgress(100, perProgress, false);
						mNotification.setContentText(mContext.getResources().getString(R.string.main_activity_update_now_download)+"	"+ perProgress +"%");
						manager.notify(0, mNotification.build());
						break;
					case 8002:// dismiss download dialog
						if(mUpdateDialog != null){
//							mUpdateDialog.setSystemDialog();
//							mUpdateDialog.needDismissDialog();
							mUpdateDialog.dismiss();
							mUpdateDialog = null;
						}
						manager.cancel(0);
						break;
					case 8003:// cutoff network & install iDesk
						// LogUtil.i(LOG_TAG, "downloadFile logout.");
						manager.cancel(0);
						PublicTools.installApk(
								mContext.getApplicationContext(),
								Environment.getExternalStorageDirectory() + "/" + mApkName);
						break;

					case 8099:
						SharedPreferences settings1 = mContext
								.getSharedPreferences(ClientConfig.settings,
										Context.MODE_APPEND);
						Editor editor1 = settings1.edit();
						editor1.putInt(
								ClientConfig.UPGRADE_APK_DOWNLOAD_STATUS,
								Constant.APK_NOT_IN_DOWNLOADING);
						editor1.commit();

						if(mThread != null){
							mThread.cancelAttach();
							mThread = null;
						}

						// mUpdateDialog = null;
						break;

					case 8110:
						SharedPreferences settings2 = mContext
								.getSharedPreferences(ClientConfig.settings,
										Context.MODE_APPEND);
						Editor editor2 = settings2.edit();
						editor2.putInt(
								ClientConfig.UPGRADE_APK_DOWNLOAD_STATUS,
								Constant.APK_DOWNLOAD_FAIL);
						editor2.commit();

						Toast.makeText(mContext, R.string.apk_download_fail,
								2000).show();

						if(mNotification != null){
							mNotification.setContentText(mContext.getResources().getString(R.string.apk_download_fail));
							manager.notify(0, mNotification.build());
						}
						
						if(mThread != null){
							mThread.cancelAttach();
							mThread = null;
						}

						// mUpdateDialog = null;
						//
						
						mInstance = null;
						break;

					}
					super.handleMessage(msg);
				}
			};
		} catch (Exception e) {
//			e.printStackTrace();
			LogUtil.i("ProgressDownloader", e.getMessage());
		}

	}

	private class MyThread extends Thread {
		Context context;

		private void onAttach(Context context) {
			this.context = context;
		}

		private void cancelAttach() {
			this.context = null;
		}

	}

	public void download() {
		if (mThread == null) {
			// LogUtil.i(LOG_TAG, "Download url:" + url);
			mHandler.sendEmptyMessage(8000);// show download dialog
			mThread = new MyThread() {
				@Override
				public void run() {
					synchronized (object) {
						IApkDownloadProcessor processor = new IApkDownloadProcessor()
	                    {
	                        @Override
	                        public void onFailure(ClientException e)
	                        {
	                        }
	                        @Override
	                        public long getFileSize(String arg0)
	                        {
	                        	return mTotalSize;
	                        }
	                        @Override
	                        public long getStartIndex(String arg0)
	                        {
	                        	return 0;
	                        }
	                        @Override
	                        public void onDownloading(InputStream is, String objectId)
	                        {
	                        	File file = null;
	                        	FileOutputStream fileOutputStream = null;
	                        	try {
	    							if (is != null) {
	    								file = new File(
	    										Environment.getExternalStorageDirectory(),
	    										mApkName);
	    								fileOutputStream = new FileOutputStream(file);
	    								byte[] buf = new byte[1024];
	    								int ch = -1;
	    								double count = 0;
	    								int currentProgress = 0;
	    								DecimalFormat df = new DecimalFormat("#");
	    								while ((ch = is.read(buf)) != -1) {
	    									fileOutputStream.write(buf, 0, ch);
	    									count += ch;
	    									String perProgress = df
	    											.format((count / mTotalSize) * 100);
	    									// if(mOnUpdateStateChangeListener != null){
	    									// mOnUpdateStateChangeListener.onDownloadAPKProgress(Integer.valueOf(perProgress));;
	    									// }
	    									int nowProgress = Integer.valueOf(perProgress);
	    									if(nowProgress == (currentProgress + 4) ){
	    										Message msg = new Message();
		    									msg.obj = nowProgress;
		    									msg.what = 8001;// update download dialog
		    									mHandler.sendMessage(msg);// update
		    									currentProgress = nowProgress;
	    									}
	    								}
	    							}
	    							
	    						} catch (Exception e) {
	    							mHandler.sendEmptyMessage(8110);
	    							e.printStackTrace();
	    							mHandler.sendEmptyMessage(8002);// dismiss download
	    															// dialog
	    						} finally {
	    							try {
	    								if (null != fileOutputStream) {
	    									fileOutputStream.flush();
	    									fileOutputStream.close();
	    								}
	    								if (null != is) {
	    									is.close();
	    								}
	    							} catch (Exception e2) {
	    								e2.printStackTrace();
	    							}
	    							if (null == file || file.length() != mTotalSize) {
	    								Log.i("info","file write error or file size is not equal real size");
	    								mHandler.sendEmptyMessage(8110);
	    							} else {//download success
	    								mHandler.sendEmptyMessage(8099);// download finish；
	    								mHandler.sendEmptyMessage(8003);// cutoff network &
	    							}
	    							mHandler.sendEmptyMessage(8002);// dismiss download
	    															// dialog
	    						}
	                        }
	                        
	                    };
	                    ApkVersionClientV2.getInstance().downloadApk(mUrl, processor);
					}
				}
			};
			mThread.onAttach(mContext);
			mThread.start();
		}
	}

	public void showProgress() {
		try {
			if (mUpdateDialog != null && !mUpdateDialog.isShowing()) {
//				mUpdateDialog.needShowDialog();
				mUpdateDialog.show();
			}else{
				if(mThread == null){
					SharedPreferences settings2 = mContext
							.getSharedPreferences(ClientConfig.settings,
									Context.MODE_APPEND);
					Editor editor2 = settings2.edit();
					editor2.putInt(
							ClientConfig.UPGRADE_APK_DOWNLOAD_STATUS,
							Constant.APK_DOWNLOAD_FAIL);
					editor2.commit();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
